package palf {
import flash.display.DisplayObject;
import flash.display.InteractiveObject;
import flash.display.Sprite;

public class IndexedSprite extends Sprite {

	private var _children : Vector.<DisplayObject> = new Vector.<DisplayObject>();
	private var _focus_index : uint;

	public function IndexedSprite() {

	}

	//------------------------------------------------------------//

	override public function addChild(child : DisplayObject) : DisplayObject {
		removeChild(child);
		_children.push(child);
		return super.addChild(child);
	}

	override public function addChildAt(child : DisplayObject, index : int) : DisplayObject {
		_children.splice(index, 0, child);
		return super.addChildAt(child, index);
	}

	//------------------------------//

	override public function removeChild(child : DisplayObject) : DisplayObject {
		var index : int = _children.indexOf(child);
		if (index > -1) {
			return removeChildAt(index);
		} else {
			return null;
		}
	}

	override public function removeChildAt(index : int) : DisplayObject {
		_children.splice(index, 1);
		return super.removeChildAt(index);
	}

	//------------------------------------------------------------//

	override public function getChildAt(index : int) : DisplayObject {
		return _children[index];
	}

	override public function getChildIndex(child : DisplayObject) : int {
		var child_index : uint = _children.indexOf(child);
		var result : int = child_index - _focus_index;
		return (result);
	}

	//------------------------------------------------------------//

	public function changeFocusIndexTo(index : int) : void {
		if (_children.length > 0) {
			_focus_index = index;
			stage.focus = InteractiveObject(_children[_focus_index]);
		} else {
			throw new Error("Gallery is empty - no child to select");
		}
	}

	public function changeFocusItemTo(child : DisplayObject) : void {
		var index : int = _children.indexOf(child);
		if (index >= 0) {
			changeFocusIndexTo(index);
		}
	}
}
}
